package com.yt.product.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.StrUtils;
import com.yt.product.models.bo.CustomerInfoSaveBO;
import com.yt.product.models.dto.CustomerInfoDTO;
import com.yt.product.models.service.ICustomerInfoService;
import com.yt.product.models.vo.CustomerInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/customerInfo")
@Slf4j
@Api(value = "CustomerInfoApiController", tags = "客户详情Api接口")
public class CustomerInfoApiController {

    @DubboReference
    private ICustomerInfoService customerInfoService;

    @ApiOperation(value = "新增客户", notes = "新增客户信息")
    @PostMapping("/add")
    public Result<CustomerInfoVO> add(@RequestBody CustomerInfoSaveBO saveBO) {
        // 调用Service层的add方法
        boolean success = customerInfoService.add(saveBO);
        if (success) {
            // 通过唯一条件查询刚插入的记录（使用phone和customerName确保唯一性）
            CustomerInfoDTO dto = customerInfoService.selectOne(
                    new EntityWrapper<CustomerInfoDTO>()
                            .eq("phone", saveBO.getPhone())
                            .eq("customer_name", saveBO.getCustomerName())
                            .eq("is_del", 0) // 排除已删除记录
            );
            if (dto == null) {
                return new Result<>(CodeEnum.FAIL_100010); // 新增成功但查询失败
            }
            // 转换DTO到VO返回（包含所有字段）
            CustomerInfoVO vo = new CustomerInfoVO();
            BeanUtils.copyProperties(dto, vo);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100007);
    }

    @ApiOperation(value = "查询客户列表（分页）", notes = "查询客户列表（支持分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "客户类型：0-个人客户，1-企业客户", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "客户状态：0-禁用，1-正常", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageNo", value = "页码（默认1）", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（默认10）", paramType = "query", dataType = "Integer")
    })
    @GetMapping("/list")
    public Result<Page<CustomerInfoVO>> list(
            String type,
            Integer status,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 构建分页对象
        Page<CustomerInfoDTO> page = new Page<>(pageNo, pageSize);

        // 构建查询条件
        EntityWrapper<CustomerInfoDTO> wrapper = new EntityWrapper<>();
        if (type != null) {
            wrapper.eq("type", type);
        }
        if (status != null) {
            wrapper.eq("status", status);
        }
        wrapper.eq("is_del", 0); // 保留逻辑删除过滤

        // 执行分页查询
        Page<CustomerInfoDTO> resultPage = customerInfoService.selectPage(page, wrapper);

        // DTO转VO处理
        List<CustomerInfoVO> voList = resultPage.getRecords().stream().map(dto -> {
            CustomerInfoVO vo = new CustomerInfoVO();
            BeanUtils.copyProperties(dto, vo);
            return vo;
        }).collect(Collectors.toList());

        // 封装分页结果
        Page<CustomerInfoVO> voPage = new Page<>();
        BeanUtils.copyProperties(resultPage, voPage);
        voPage.setRecords(voList);

        return new Result<>(voPage);
    }

    @ApiOperation(value = "查询客户详情", notes = "根据ID查询客户详情")
    @ApiImplicitParam(name = "id", value = "客户ID", required = true, paramType = "path", dataType = "Long")
    @GetMapping("/get/{id}")
    public Result<CustomerInfoVO> get(@PathVariable Long id) {
        if (id == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        CustomerInfoDTO dto = customerInfoService.selectById(id);
        if (dto == null || dto.getIsDel() == 1) {
            return new Result<>(CodeEnum.FAIL_100010); // 记录不存在
        }

        CustomerInfoVO vo = new CustomerInfoVO();
        BeanUtils.copyProperties(dto, vo);
        return new Result<>(vo);
    }

    @ApiOperation(value = "更新客户", notes = "根据ID更新客户信息")
    @PutMapping("/update/{id}")
    public Result<CustomerInfoVO> update(
            @PathVariable Long id,
            @RequestBody CustomerInfoSaveBO saveBO) {

        // 校验记录是否存在
        CustomerInfoDTO existingDto = customerInfoService.selectById(id);
        if (existingDto == null || existingDto.getIsDel() == 1) {
            return new Result<>(CodeEnum.FAIL_100010); // 记录不存在或已删除
        }

        // 复制更新字段并设置ID
        CustomerInfoDTO updateDto = new CustomerInfoDTO();
        BeanUtils.copyProperties(saveBO, updateDto);
        updateDto.setId(id);
        updateDto.setUpdateTime(new Date());

        boolean success = customerInfoService.updateById(updateDto);
        if (success) {
            // 查询更新后的最新记录
            CustomerInfoDTO updatedDto = customerInfoService.selectById(id);
            CustomerInfoVO vo = new CustomerInfoVO();
            BeanUtils.copyProperties(updatedDto, vo);
            return new Result<>(vo);
        }
        return new Result<>(CodeEnum.FAIL_100008);
    }

    @ApiOperation(value = "删除客户", notes = "逻辑删除客户")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        // 先校验记录是否存在
        CustomerInfoDTO dto = customerInfoService.selectById(id);
        if (dto == null || dto.getIsDel() == 1) {
            return new Result<>(CodeEnum.FAIL_100010); // 记录不存在或已删除
        }

        // 执行逻辑删除
        dto.setIsDel(1);
        dto.setUpdateTime(new Date());
        boolean success = customerInfoService.updateById(dto);
        return success ? new Result<>() : new Result<>(CodeEnum.FAIL_100009);
    }

    @ApiOperation(value = "按名称模糊查询客户（分页）", notes = "根据客户名称模糊查询匹配结果（自动过滤已删除记录）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "customerName", value = "客户名称（模糊匹配）", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNo", value = "页码（默认1）", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数（默认10）", paramType = "query", dataType = "Integer")
    })
    @GetMapping("/searchByName")
    public Result<Page<CustomerInfoVO>> searchByName(
            String customerName,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 构建分页对象
        Page<CustomerInfoDTO> page = new Page<>(pageNo, pageSize);

        // 构建查询条件
        EntityWrapper<CustomerInfoDTO> wrapper = new EntityWrapper<>();
        if (StrUtils.isNotEmpty(customerName)) {
            wrapper.like("customer_name", customerName);
        }
        wrapper.eq("is_del", 0); // 排除已删除记录

        // 执行分页查询
        Page<CustomerInfoDTO> resultPage = customerInfoService.selectPage(page, wrapper);

        // DTO转VO处理
        List<CustomerInfoVO> voList = resultPage.getRecords().stream()
                .map(dto -> {
                    CustomerInfoVO vo = new CustomerInfoVO();
                    BeanUtils.copyProperties(dto, vo);
                    return vo;
                })
                .collect(Collectors.toList());

        // 封装分页结果
        Page<CustomerInfoVO> voPage = new Page<>();
        BeanUtils.copyProperties(resultPage, voPage);
        voPage.setRecords(voList);

        return new Result<>(voPage);
    }
}